package top.zywork.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.zywork.common.BeanUtils;
import top.zywork.dao.GoodsCartDAO;
import top.zywork.dos.GoodsCartDO;
import top.zywork.dto.GoodsCartDTO;
import top.zywork.query.GoodsCartQuery;
import top.zywork.service.AbstractBaseService;
import top.zywork.service.GoodsCartService;

import javax.annotation.PostConstruct;

/**
 * GoodsCartServiceImpl服务接口实现类<br/>
 *
 * 创建于2019-07-03<br/>
 *
 * @author http://zywork.top 王振宇
 * @version 1.0
 */
@Service(value = "goodsCartService")
public class GoodsCartServiceImpl extends AbstractBaseService implements GoodsCartService {

    private GoodsCartDAO goodsCartDAO;

    @Override
    public int save(Object dataTransferObj) {
        GoodsCartDTO goodsCartDTO = (GoodsCartDTO) dataTransferObj;
        GoodsCartQuery goodsCartQuery = GoodsCartQuery.builder().userId(goodsCartDTO.getUserId()).goodsSkuId(goodsCartDTO.getGoodsSkuId()).build();
        if (goodsCartDAO.countByCondition(goodsCartQuery) > 0) {
            // 此sku已经在用户的购物车中，则更新
            int updateRows = goodsCartDAO.updateQuantity(BeanUtils.copy(dataTransferObj, GoodsCartDO.class));
            return updateRows == 1 ? updateRows : -1;
        }
        return goodsCartDAO.save(BeanUtils.copy(dataTransferObj, GoodsCartDO.class));
    }

    @Autowired
    public void setGoodsCartDAO(GoodsCartDAO goodsCartDAO) {
        super.setBaseDAO(goodsCartDAO);
        this.goodsCartDAO = goodsCartDAO;
    }

    @PostConstruct
    public void init() {
        super.init(GoodsCartDO.class, GoodsCartDTO.class);
    }
}
